from django.contrib.auth import login, authenticate, logout
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django import http
from django.views import View
from django_redis import get_redis_connection
import json
import re

from celery_tasks.email.tasks import send_verify_email
from meiduo_mall.utils.views import LoginRequestMixin
from users.models import User, Address
import logging
logger = logging.getLogger('django')

class UsernameCountView(View):
    #     1查询username在数据库的个数
    def get(self, request, username):
        try:
            conut = User.objects.filter(username=username).count()
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '访问数据库失败'
                                 })
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'count': conut
        })


class MobileCountView(View):
    def get(selfdelf, request, mobile):
        # 判断手机号是否重复注册
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'errmsg': '查询数据库出错',
            })
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'count': count,
        })

# 注册接口
class RegisterView(View):
    def post(self, request):
        dict = json.loads((request.body.decode()))
        username = dict.get('username')
        password = dict.get('password')
        password2 = dict.get('password2')
        mobile = dict.get('mobile')
        sms_code = dict.get('sms_code')
        allow = dict.get('allow')
        if not all([username, password, password2, mobile, sms_code, allow]):
            return JsonResponse({
                'code': 400,
                'errmsg': '缺少必传参数'
            })
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({
                'code': 400,
                'errmsg': 'username格式错误'
            })
        if not re.match(r'^[a-zA-Z0-9_-]{8,20}$', password):
            return JsonResponse({
                'code': 400,
                'errmsg': 'password格式错误'
            })
        if password != password2:
            return JsonResponse({
                'code': 400,
                'errmsg': '两次输入不对'
            })
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({
                'code': 400,
                'errmsg': 'mobile格式错误'
            })
        if allow != True:
            return JsonResponse({
                'code': 400,
                'errmsg': '协议没同意'
            })
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if sms_code != sms_code_server.decode():
            return JsonResponse({
                'code': 400,
                'errmsg': '验证码错误'
            })
        try:
            user = User.objects.create_user(username=username,
                                            password=password,
                                            mobile=mobile)
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'errmsg': '保存数据库出错'
            })

        login(request, user)
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok'
        })

# 登录接口
class LoginView(View):
    def post(self, request):
        dict = json.loads(request.body.decode())
        username = dict.get('username')
        password = dict.get('password')
        remembered = dict.get('remembered')
        if not all([username, password]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

            # 3.验证是否能够登录
        user = authenticate(username=username,
                            password=password)

        # 判断是否为空,如果为空,返回
        if user is None:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '用户名或者密码错误'})

        # 4.状态保持
        login(request, user)

        # 5.判断是否记住用户
        if remembered != True:
            # 7.如果没有记住: 关闭立刻失效
            request.session.set_expiry(0)
        else:
            # 6.如果记住:  设置为两周有效
            request.session.set_expiry(None)

        response = http.JsonResponse({'code': 0,
                                      'errmsg': 'ok'})
        response.set_cookie('username',
                            user.username,
                            max_age=3600 * 24.14)
        # 8.返回json
        return response

# 退出登录
class LogoutView(View):
    def delete(self, request):
        # 1.清理session
        logout(request)
        # 2.创建response对象
        response = JsonResponse({
            'code': 0,
            'errmsg': 'ok'
        })
        # 3.调用对象的delete_cookie
        response.delete_cookie('username')
        return response

# 用户中心渲染接口
class UserInfoView(LoginRequestMixin, View):
    def get(self, request):
        dict = { "username":request.user.username,
           "mobile":request.user.mobile,
           "email": request.user.email,
           "email_active": request.user.email_active}
        return JsonResponse({
            'code':0,
            'errmsg':'ok',
            'info_data':dict
        })
# 绑定邮箱
class EmailView(View):
    def put(self,request):
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')
        if not email:
            return http.JsonResponse({
                'code':400,
                'errmsg':'缺少参数'
            })
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$',email):
            return JsonResponse({
                'code':400,
                'errmsg':'参数email有误'
            })
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({
                'code':400,
                'errmsg':'添加邮箱失败'
            })
        verify_url = request.user.generate_verify_email_url()
        send_verify_email.delay(email, verify_url)
        return JsonResponse({
            'code':0,
            'errmsg':'ok'
        })
class VerifyEmailView(View):
    def put(self,request):
        token = request.GET.get('token')
        # 校验参数：判断 token 是否为空和过期，提取 user
        if not token:
            return JsonResponse({
                'code':400,
                'errmsg':'缺少token'
            })
        user = User.check_verify_email_token(token)
        if not user:
            return http.JsonResponse({'code':400,
                                  'errmsg':'无效的token'})
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '激活邮件失败'})

            # 返回邮箱验证结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': 'ok'})

class CreateAddressView(View):
    def post(self, request):
        try:
            count = Address.objects.filter(user=request.user,
                                   is_deleted=False).count()
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'errmsg': '获取用户地址出错'
            })
        if count >= 20:
            return JsonResponse({
                'code':400,
                'errrmsg':'超出地址上限'
            })
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        if not all([receiver,province_id,city_id,district_id,place,mobile]):
            return JsonResponse({
                'code':400,
                'errmsg':'缺少参数'
            })
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数email有误'})
        try:
            address = Address.objects.create(
                user = request.user,
                title = receiver,
                receiver = receiver,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email
            )
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            return JsonResponse({
                'code':400,
                'errmsg':'ok',
            })
        address_dict = {
            "id":address.id,
            "title":address.title,
            "reveiver":address.receiver,
            "province":address.province.name,
            "city":address.city.name,
            "district":address.district.name,
            "place":address.place,
            "mobile":address.mobile,
            "tel":address.tel,
            "email":address.email
        }
        return JsonResponse({
            'code':0,
            'errmsg':'ok',
            'address':address_dict
        })
class AddressView(View):
    def get(self,request):
        addresses = Address.objects.filter(user = request.user,
                                         is_deleted = False)
        address_dict_list = []
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver":address.receiver,
                "province":address.province.name,
                "city":address.city.name,
                "district":address.district.name,
                "place":address.place,
                "mobile":address.mobile,
                "tel":address.tel,
                "email":address.email,

            }

            default_address = request.user.default_address
            if default_address.id == address.id:
                address_dict_list.insert(0,address_dict)
            else:
                address_dict_list.append(address_dict)
        default_id = request.user.default_address_id
        return JsonResponse({
            'code':0,
            'errmsg':'ok',
            'addresses': address_dict_list,
            'default_address_id': default_id
        })
class UpdateDestroyAddressView(View):
    def put(self,request,address_id):
        '''修改地址'''
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        # 校验参数
        if not all([receiver,province_id,city_id,district_id,place,mobile]):
            return JsonResponse({
                'code':400,
                'errmsg':'缺少参数'
            })
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数email有误'})
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '更新地址失败'})
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return http.JsonResponse({'code': 0,
                                  'errmsg': '更新地址成功',
                                  'address': address_dict})

    def delete(self,request,address_id):
        try:
            address = Address.objects.get(id=address_id)
            address.is_deleted = True
            address.save()
        except Exception as e:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '删除地址失败'})
        return http.JsonResponse({'code': 0,
                                  'errmsg': '删除地址成功'})
class DefaultAddressView(View):
    def put(self,request,address_id):
        try:
            address = Address.objects.get(id=address_id)
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '设置默认地址失败'})
        return http.JsonResponse({'code': 0,
                                  'errmsg': '设置默认地址成功'})
class UpdateTitleAddressView(View):
    def put(self,request,address_id):
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        try:
            address = Address.objects.get(id=address_id)

            # 设置新的地址标题
            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '设置地址标题失败'})

            # 4.响应删除地址结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '设置地址标题成功'})
class ChangPasswordView(View):
    def put(self,request):
        dict = json.loads(request.body.decode())
        old_password = dict.get('old_password')
        new_password = dict.get('new_password')
        new_password2 = dict.get('new_password2')

        if not all([old_password, new_password, new_password2]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})
        # ********
        result = request.user.check_password(old_password)

        if not result:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '原始密码不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '密码最少8位,最长20位'})

        if new_password != new_password2:
            return http.JsonResponse({'code': 400,
                                      'errmsg': '两次输入密码不一致'})
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': '修改密码失败'})

            # 清理状态保持信息
        logout(request)

        response = http.JsonResponse({'code': 0,
                                      'errmsg': 'ok'})

        response.delete_cookie('username')

        # # 响应密码修改结果：重定向到登录界面
        return response